package org.jeecg.modules.iot.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.util.Base64Utils;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.iot.devices.entity.Devices;
import org.jeecg.modules.iot.devices.service.IDevicesService;
import org.jeecg.modules.iot.devicesrecord.entity.DevicesRecord;
import org.jeecg.modules.iot.devicesrecord.service.IDevicesRecordService;
import org.jeecg.modules.iot.utils.HttpClient4;
import org.jeecg.modules.iot.utils.HttpUtils;
import org.jeecg.modules.iot.utils.KyqApiUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import com.alibaba.fastjson.JSON;
import java.util.*;

@RestController
@RequestMapping("/iot")
@Slf4j
public class IotController{
    @Autowired
    private IDevicesService devicesService;
    @Autowired
    private IDevicesRecordService devicesRecordService;
    private String uploadPath="D:/iotFiles";
    @PostMapping(value = "/remoteCheck")
    @AutoLog(value = "链接测试")
    @ApiOperation(value = "链接测试", notes = "链接测试")
    public String remoteCheck(@RequestBody  JSONObject prams ){
       /* JSONObject  jsonObject =new JSONObject ();
        jsonObject.put("sn",prams.get("sn"));
        jsonObject.put("verifyType",2);
        jsonObject.put("identifyNo","");
        jsonObject.put("visitorType","");
        jsonObject.put("turnstileAddress","德宏联通");
        jsonObject.put("picture",prams.get("picture"));*/
        //String kyqUrl="http://106.60.78.73:9000/turnstile/nucleicAcidTest";
        //String kyqUrl="http://106.60.78.73:9000/turnstile/remoteCheck";
        //String rs= HttpUtils.httpPost(kyqUrl,prams);
        //System.out.println("===rs==="+rs);
        JSONObject rsObj =new JSONObject();
        JSONObject remoteCheck=new JSONObject();
        JSONObject info=new JSONObject();
        JSONObject userInfo=new JSONObject();
                    userInfo.put("faceDataType",1);
                    userInfo.put("cardtype","");
                    userInfo.put("cardNum","533103198810201232");
                    userInfo.put("name","姜占明");
                    userInfo.put("gender",1);
                    userInfo.put("face_picurl","https://www.kyq.dh.gov.cn/imgFile/2021/07/28/1627441737226961023360.jpg");
                    userInfo.put("face_picdata","");
                info.put("encodeType","utf8");
                info.put("prompts","欢迎您 姜占明");
                info.put("userInfo",userInfo);
            remoteCheck.put("serialNo",prams.get("serialNo"));
            remoteCheck.put("checkResult","success");
            remoteCheck.put("info",info);
        rsObj.put("status",1);
        rsObj.put("msg","success");
        rsObj.put("errorCode",0);
        rsObj.put("remoteCheck",remoteCheck);
        System.out.println(rsObj);
        return rsObj.toString();
    }

    @PostMapping(value = "/dumuHeart")
    @AutoLog(value = "度目心跳")
    @ApiOperation(value = "度目心跳", notes = "度目心跳")
    public void dumuHeart(@RequestBody  ArrayList<Map> prams){
        if(prams!=null){
            String tags= (String) prams.get(0).get("tags");
            String sn=tags.split(",")[0].split("=")[1];
            //通过设备sn查询系统中设备登记的信息
            QueryWrapper<Devices> queryWrapper =new QueryWrapper<>();
            queryWrapper.eq("dev_sn",sn);
            Devices dev=devicesService.getOne(queryWrapper);
            if(dev!=null){
                dev.setHeartData(JSONObject.toJSONString(prams));
                System.out.println("心跳："+JSONObject.toJSONString(prams));
                dev.setHeartTime(new Date());
                devicesService.updateById(dev);
            }
        }

    }
    @PostMapping(value = "/demuFace")
    @AutoLog(value = "抓拍上传")
    @ApiOperation(value = "抓拍上传", notes = "抓拍上传")
    public String demuFace(@RequestBody  JSONObject prams ){
        System.out.println(prams.toString());
        String sn=(String) prams.get("xeye_id");
        if(StringUtils.isNotEmpty(sn)){
            ArrayList<LinkedHashMap> facesObj= (ArrayList) prams.get("faces");
            for(LinkedHashMap fobj:facesObj){
                String face= (String) fobj.get("face_img");
                if(face.indexOf("data:image/")==-1){
                    face="data:image/jpg;base64,"+face;
                }
                if(StringUtils.isNotEmpty(face)){
                    //通过设备sn查询系统中设备登记的信息
                    QueryWrapper<Devices> queryWrapper =new QueryWrapper<>();
                    queryWrapper.eq("dev_sn",sn);
                    Devices dev=devicesService.getOne(queryWrapper);
                    if(dev!=null&&!dev.getDevStatus().equals(2)){//如果设备未在系统中进行登记，或者设备已标记为“删除”，则不对抓拍做任何处理
                        DevicesRecord drd=new DevicesRecord();
                        //设备信息
                        drd.setDevSn(sn);//设备编号sn
                        drd.setDevName(dev.getDevName());
                        drd.setDevAddress(dev.getDevAddress()+"-"+dev.getDevAddressDetail());
                        drd.setDevType(dev.getDevType());
                        drd.setDevLocation(dev.getDevLocation());
                        drd.setDevDirection(dev.getDevDirection());//方向
                        //将认证信息传到抗疫情中进行认证并获得人员信息
                        JSONObject kyqRs= KyqApiUtils.faceCheck(face);
                        //人员信息
                        if(kyqRs!=null&&kyqRs.getInteger("status").equals(1)){
                            JSONObject remoteCheck = (JSONObject) kyqRs.get("remoteCheck");
                            JSONObject info = (JSONObject) remoteCheck.get("info");
                            JSONObject userInfo = (JSONObject) info.get("userInfo");
                            drd.setAuthKyq(kyqRs.getString("msg"));
                            if(userInfo!=null){
                                drd.setPsnCardno(userInfo.getString("cardNum"));//身份证号码
                                drd.setKyqFace(userInfo.getString("face_picurl"));//抗疫情中的人脸
                          /*  if(StringUtils.isNotEmpty(userInfo.getString("cardNum"))){
                                //当客户获取到人员身份证时，通过身份证及设备的的关联，进行查询是区内人员还是访客
                                //drd.setPsnType();
                            }*/
                                drd.setPsnName(userInfo.getString("name"));//姓名
                                drd.setPsnGender(userInfo.getInteger("gender"));//性别
                                // drd.setPsnNat();//国籍
                            }else{
                                drd.setRemarks("抗疫情:"+info.getString("prompts"));
                            }
                        }
                        //保存抓拍记录
                        drd.setAuthMode(2);
                        drd.setAuthTime(new Date());
                        MultipartFile file= Base64Utils.base64ToMultipart(face);
                        String bizPath=sn+"/"+ DateUtils.date2Str(new Date(),DateUtils.date_sdf.get());//保存路径为"设备号/当天日期"
                         //String faceUrl = CommonUtils.upload(file, bizPath, CommonConstant.UPLOAD_TYPE_MINIO);
                        String faceUrl = CommonUtils.uploadLocal(file, bizPath, uploadPath);
                        drd.setPsnFace(faceUrl);//抓怕到的人像
                        devicesRecordService.save(drd);
                    }
                }
            }
        }
        return "{}";
    }

    public static void main(String[] args){
        // import org.apache.commons.httpclient.HttpClient;
     /*   String url = "http://192.168.18.84:80/ISAPI/System/deviceInfo";
        HttpClient client = new HttpClient();
        // 设置用户名和密码
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials("admin", "admin12345");
        client.getState().setCredentials(AuthScope.ANY, creds);
        GetMethod method = new GetMethod(url);
        method.setDoAuthentication(true);
        int statusCode = client.executeMethod(method);
        byte[] responseData = method.getResponseBodyAsString().getBytes(method.getResponseCharSet());
        String strResponseData = new String(responseData, "utf-8");
        method.releaseConnection();
        // 输出接收的消息
        System.out.println(strResponseData);*/
    }
}
